# include "scene.h"
# include <stdio.h>
# include <time.h>
# include <errno.h>
# include <string.h>

extern short print_recov(const struct grid *g)
  {
   int _errno;
   unsigned short i, j, k, tn, isec;
   FILE *ptr;
   char fname[MAX_FNAME_LEN];
   struct tm local_t;
   time_t tnow;

   tnow = time((time_t)0);
   localtime_r(&tnow, &local_t);

   sprintf(fname, "%02d.%s.%04d-%02d-%02d.dat", RUN_CNT, RECOV_FILE, 1900+local_t.tm_year, local_t.tm_mon+1, local_t.tm_mday);

   if((ptr = (FILE *)fopen(fname, "w")) == (FILE *)0)
     {
      _errno = errno;
      fprintf(g->lptr, "WARNING:: In 'print_recov()': Unable to open the recovery-file '%s' for writing.\n\tSystem errno = %d.\nNo recovery file is being written.\n", fname, _errno);
      return -1;
     }

/* Printing information related to time to which this recovery file corresponds. */
   fprintf(ptr, "# IMPORTANT: Don't edit this file.\n# Variables:\t\"time-instant (in Sec)\"\t\"time-step (last-->present) (in Sec)\"\n%0.15E\t%0.15E\n", g->t, g->dt);

/* Printing for internal parts of the SECTION-1~3. */
   for(isec = 0; isec < Nsec; isec++)
      {
       fprintf(ptr, "\n# ------------- SECTION - %d -------------\n", isec+1);
       fprintf(ptr, "# Variables:\tu(i,j,k, t)\tv(i,j,k, t)\tw(i,j,k, t)\tp(i,j,k, t)");
#      ifdef SOLVE_ENERGY
       fprintf(ptr, "\tT(i,j,k, t)");
#      endif
       fprintf(ptr, "\n");

       for(i = 0; i < g->nr[isec]+2*NrG; i++) for(j = 0; j < g->nth+2*NthG; j++) for(k = 0; k < g->nz[isec]+2*NzG; k++)
            {
             fprintf(ptr, "%0.15E\t%0.15E\t%0.15E\t%0.15E", g->u[isec][i][j][k], g->v[isec][i][j][k], g->w[isec][i][j][k], g->p[isec][i][j][k]);
#            ifdef SOLVE_ENERGY
             fprintf(ptr, "\t%0.15E", g->T[isec][i][j][k]);
#            endif
             fprintf(ptr, "\n");
            }
     }


/* Printing data at outlet of the SECTION-3 to be used in application of Orlansky BC. */
   for(tn = 0; tn <= tn_BACKUP-2; tn++ )
       {
        fprintf(ptr, "\n# Data at outlet at time \"t - %d*dt\" (used to determine phase velocities while applying the Orlansky BC).\n# Variables:\tu(i,j,k, t)\tv(i,j,k, t)\tw(i,j,k, t)", tn+1);
#       ifdef SOLVE_ENERGY
        fprintf(ptr, "\tT(i,j,k, t)");
#       endif
        fprintf(ptr, "\n");

        for(i = 0; i < g->nr_gap; i++) for(j = 0; j < g->nth; j++) for(k = 0; k < zCells_BACKUP; k++)
              {
               fprintf(ptr, "%0.15E\t%0.15E\t%0.15E", g->outBC.u[tn][i][j][k], g->outBC.v[tn][i][j][k], g->outBC.w[tn][i][j][k]);
#              ifdef SOLVE_ENERGY
               fprintf(ptr, "\t%0.15E", g->outBC.T[tn][i][j][k]);
#              endif
               fprintf(ptr, "\n");
              }
       }

   fclose(ptr);

   if(g->tptr != (FILE *)0) fprintf(g->tptr, "\tRecovery file, '%s', is written!\n", fname);

   return 1;
  }
